package com.bigdatan.b2c.controller.glass;

import com.bigdatan.b2c.controller.AbstractController;
import com.bigdatan.b2c.controller.glass.vo.MainADVO;
import com.bigdatan.b2c.entity.Ad;
import com.bigdatan.b2c.service.IAdService;
import com.google.gson.Gson;
import constant.SystemCode;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import util.JsonResponse;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shangdong on 17/5/13.
 */
@RestController
@RequestMapping("/api")
public class GlassAdController extends AbstractController {

    @Resource
    private IAdService adService;

    public static final Gson gson = new Gson();

    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET},value = "/ads")
    public JsonResponse<List<MainADVO>> getAds() {
        JsonResponse<List<MainADVO>> result = new JsonResponse<>();
        List<Ad> all = adService.getAll();
        all.remove(0);
        List<MainADVO> res = new ArrayList<>();
        if (all.size() != 0) {
            for (Ad ad : all) {
                MainADVO mainADVO = new MainADVO();
                BeanUtils.copyProperties(ad,mainADVO,"description");
                MainADVO.DescVO descVO = gson.fromJson(ad.getDescription(), MainADVO.DescVO.class);
                mainADVO.setDescription(descVO);
                res.add(mainADVO);
            }
            result.setRes(SystemCode.SUCCESS);
            result.setObj(res);
        } else {
            result.setRes(SystemCode.FAILURE);
        }
        return result;
    }


    //@GetMapping("/queryAdByAdId")
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET},value = "/mainad")
    public JsonResponse<MainADVO> mainAd() {
        JsonResponse<MainADVO> result = new JsonResponse<>();
        try {
            Ad ad = adService.selectByPrimaryKey(1);
            MainADVO mainADVO = new MainADVO();
            BeanUtils.copyProperties(ad,mainADVO,"description");
            MainADVO.DescVO descVO = gson.fromJson(ad.getDescription(), MainADVO.DescVO.class);
            mainADVO.setDescription(descVO);
            result.setRes(SystemCode.SUCCESS);
            result.setObj(mainADVO);
        } catch (Exception e) {
            result.setRes(SystemCode.FAILURE);
        }

        return result;
    }
}
